package com.shoes.controller;

import com.alibaba.fastjson.JSON;
import com.shoes.model.ResponseDO;
import com.shoes.service.UserService;
import com.shoes.service.impl.LoginManager;
import com.shoes.utils.LoggerUtil;
import com.shoes.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author asen
 */
@Controller
@RequestMapping(value = "/user", produces = {"application/json;charset=UTF-8"})
public class UserController {

    private UserService userService;
    private LoginManager loginManager;

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public String getUserInfo(HttpServletRequest request)
            throws ServletException, IOException {
        ResponseDO result;

        try {
            long userId = Long.parseLong(request.getParameter("user_id"));
            long toUid = Long.parseLong(request.getParameter("to_uid"));

            result = userService.getUserInfo(userId, toUid);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            result = new ResponseDO(ResultCode.PARAMETER_ERROR, null, null);
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResponseDO(ResultCode.GLOBAL_FAILED, null, null);
        }

        String data = JSON.toJSONString(result);
        LoggerUtil.logger.info(" Response ResultCode: " + result.getResultCode());
        LoggerUtil.logger.info(" Response Content:\n" + data);
        return data;
    }

    @RequestMapping(value = "/getAuthCode", method = RequestMethod.POST)
    @ResponseBody
    public String getAuthCode(HttpServletRequest request)
            throws ServletException, IOException {
        ResponseDO result;

        try {
            String phoneNumber = request.getParameter("phone_number");
            HttpSession session = request.getSession(true);
            Integer sendCode = null;
            if(session.getAttribute(phoneNumber) != null) {
                sendCode = Integer.parseInt((String) session.getAttribute(phoneNumber));
            }
            result = userService.getAuthCode(phoneNumber, sendCode);
            Integer authCode = (Integer) result.getData();
            if(authCode != null) {
                session.setAttribute(phoneNumber, authCode + "");
                session.setMaxInactiveInterval(10*60);
                result = new ResponseDO(ResultCode.GLOBAL_SUCCESSFUL, null, null);
            } else {
                result = new ResponseDO(ResultCode.GLOBAL_FAILED, null, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResponseDO(ResultCode.GLOBAL_FAILED, null, null);
        }
        String data = JSON.toJSONString(result);
        LoggerUtil.logger.info(" Response ResultCode: " + result.getResultCode());
        LoggerUtil.logger.info(" Response Content:\n" + data);
        return data;
    }

    @RequestMapping(value = "/checkAuthCode", method = RequestMethod.POST)
    @ResponseBody
    public String checkAuthCode(HttpServletRequest request)
            throws ServletException, IOException {
        ResponseDO result;

        String authCode = request.getParameter("auth_code");
        String phoneNumber = request.getParameter("phone_number");

        if(phoneNumber != null && authCode != null) {
            HttpSession session = request.getSession(false);
            if(session != null) {
                String auth = (String) session.getAttribute(phoneNumber);
                LoggerUtil.logger.info("验证手机验证码：" + "\r\n 手机号：" + phoneNumber + "\t服务器验证码：" + auth);
                if(auth != null && auth.equals(authCode)) {
                    result = new ResponseDO(ResultCode.GLOBAL_SUCCESSFUL, null);
                } else {
                    result = new ResponseDO(ResultCode.AUTH_CODE_ERROR, null);
                }
            } else {
                result = new ResponseDO(ResultCode.AUTH_CODE_EXPIRE, null);
            }
        } else {
            result = new ResponseDO(ResultCode.PARAMETER_ERROR, null);
        }

        String data = JSON.toJSONString(result);
        LoggerUtil.logger.info(" Response ResultCode: " + result.getResultCode());
        LoggerUtil.logger.info(" Response Content:\n" + data);
        return data;
    }

    @RequestMapping(value = "/checkRegister", method = RequestMethod.POST)
    @ResponseBody
    public String checkRegister(HttpServletRequest request)
            throws ServletException, IOException {
        ResponseDO result;

        try {
            String phoneNumber = request.getParameter("phone_number");

            result = userService.checkRegister(phoneNumber);
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResponseDO(ResultCode.GLOBAL_FAILED, null, null);
        }

        String data = JSON.toJSONString(result);
        LoggerUtil.logger.info(" Response ResultCode: " + result.getResultCode());
        LoggerUtil.logger.info(" Response Content:\n" + data);
        return data;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public String login(HttpServletRequest request)
            throws ServletException, IOException {
        ResponseDO result;

        try {
            String phone = request.getParameter("phone_number");
            String password = request.getParameter("password");

            result = userService.userLogin(phone, password);
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResponseDO(ResultCode.GLOBAL_FAILED, null, null);
        }

        if(result.getResultCode() == ResultCode.GLOBAL_SUCCESSFUL) {
            long userId = Long.valueOf(result.getData().toString());
            String token = loginManager.processAfterLogin(request, userId, true, false);
            result.setData(loginManager.getLoginJSONData(userId, token));
        }

        String data = JSON.toJSONString(result);
        LoggerUtil.logger.info(" Response ResultCode: " + result.getResultCode());
        LoggerUtil.logger.info(" Response Content:\n" + data);
        return data;
    }

    @RequestMapping(value = "/tokenLogin", method = RequestMethod.POST)
    @ResponseBody
    public String tokenLogin(HttpServletRequest request)
            throws ServletException, IOException {
        ResponseDO result;

        try {
            String phone = request.getParameter("phone_number");
            String password = request.getParameter("password");

            result = userService.userLogin(phone, password);
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResponseDO(ResultCode.GLOBAL_FAILED, null, null);
        }

        if(result.getResultCode() == ResultCode.GLOBAL_SUCCESSFUL) {
            long userId = Long.valueOf(result.getData().toString());
            String token = loginManager.processAfterLogin(request, userId, true, false);
            result.setData(loginManager.getLoginJSONData(userId, token));
        }

        String data = JSON.toJSONString(result);
        LoggerUtil.logger.info(" Response ResultCode: " + result.getResultCode());
        LoggerUtil.logger.info(" Response Content:\n" + data);
        return data;
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public String register(HttpServletRequest request)
            throws ServletException, IOException {
        ResponseDO result;

        try {
            String phone = request.getParameter("phone_number");
            String password = request.getParameter("password");

            HttpSession session = request.getSession(false);
            if(session != null) {
                session.removeAttribute(phone);
            }
            result = userService.userRegister(phone, password);
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResponseDO(ResultCode.GLOBAL_FAILED, null, null);
        }
        if(result.getResultCode() == ResultCode.GLOBAL_SUCCESSFUL) {
            /**注册成功，默认立刻登入*/
            long userId = Long.valueOf(result.getData().toString());
            String token = loginManager.processAfterLogin(request, userId, true, true);
            result.setData(loginManager.getLoginJSONData(userId, token));
        }

        String data = JSON.toJSONString(result);
        LoggerUtil.logger.info(" Response ResultCode: " + result.getResultCode());
        LoggerUtil.logger.info(" Response Content:\n" + data);
        return data;
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public String logout(HttpServletRequest request)
            throws ServletException, IOException {
        ResponseDO result;

        try {
            String userId = request.getParameter("user_id");

            result = userService.userLogout(userId);
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResponseDO(ResultCode.GLOBAL_FAILED, null, null);
        }

        String data = JSON.toJSONString(result);
        LoggerUtil.logger.info(" Response ResultCode: " + result.getResultCode());
        LoggerUtil.logger.info(" Response Content:\n" + data);
        return data;
    }

    @RequestMapping(value = "/thirdPartyRegister", method = RequestMethod.POST)
    @ResponseBody
    public String thirdPartyRegister(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ResponseDO result;

        try {
            String type = request.getParameter("type");
            String account = request.getParameter("account");

            result = userService.thirdPartyRegister(type, account);
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResponseDO(ResultCode.GLOBAL_FAILED, null, null);
        }

        String data = JSON.toJSONString(result);
        LoggerUtil.logger.info(" Response ResultCode: " + result.getResultCode());
        LoggerUtil.logger.info(" Response Content:\n" + data);
        return data;
    }

    @RequestMapping(value = "/thirdPartyLogin", method = RequestMethod.POST)
    @ResponseBody
    public String thirdPartyLogin(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ResponseDO result;

        try {
            String type = request.getParameter("type");
            String account = request.getParameter("account");
            String token = request.getParameter("token");

            result = userService.thirdPartyLogin(type, account, token);
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResponseDO(ResultCode.GLOBAL_FAILED, null, null);
        }

        String data = JSON.toJSONString(result);
        LoggerUtil.logger.info(" Response ResultCode: " + result.getResultCode());
        LoggerUtil.logger.info(" Response Content:\n" + data);
        return data;
    }

    @RequestMapping(value = "/changePsw", method = RequestMethod.POST)
    @ResponseBody
    public String changePsw(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ResponseDO result;

        try {
            long userId = Long.parseLong(request.getParameter("user_id"));
            String oldPassword = request.getParameter("old_password");
            String newPassword = request.getParameter("new_password");

            result = userService.changePassword(userId, oldPassword, newPassword);
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResponseDO(ResultCode.GLOBAL_FAILED, null, null);
        }

        String data = JSON.toJSONString(result);
        LoggerUtil.logger.info(" Response ResultCode: " + result.getResultCode());
        LoggerUtil.logger.info(" Response Content:\n" + data);
        return data;
    }

    @RequestMapping(value = "/resetPsw", method = RequestMethod.POST)
    @ResponseBody
    public String resetPsw(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ResponseDO result;

        try {
            String phoneNumber = request.getParameter("phone_number");
            String newPassword = request.getParameter("new_password");

            result = userService.resetPassword(phoneNumber, newPassword);
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResponseDO(ResultCode.GLOBAL_FAILED, null, null);
        }

        String data = JSON.toJSONString(result);
        LoggerUtil.logger.info(" Response ResultCode: " + result.getResultCode());
        LoggerUtil.logger.info(" Response Content:\n" + data);
        return data;
    }

    @RequestMapping(value = "/setup", method = RequestMethod.POST)
    @ResponseBody
    public String setUp(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ResponseDO result;

        long userId = Long.parseLong(request.getParameter("user_id"));
        String infoJson = request.getParameter("info_json");

        result = new ResponseDO(ResultCode.GLOBAL_SUCCESSFUL, null, null);
        String data = JSON.toJSONString(result);
        LoggerUtil.logger.info(" Response ResultCode: " + result.getResultCode());
        LoggerUtil.logger.info(" Response Content:\n" + data);
        return data;
    }

    public UserService getUserService() {
        return userService;
    }
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public LoginManager getLoginManager() {
        return loginManager;
    }
    @Autowired
    public void setLoginManager(LoginManager loginManager) {
        this.loginManager = loginManager;
    }
}
